
import axios from 'axios';
import { app, BrowserWindow, shell, ipcMain } from 'electron'
import { ChildProcessPool, StaticThreadPool } from 'electron-re'
import path from 'path'
import * as Cheerio from 'cheerio';
import Piscina from 'piscina';
// import {getResultByKeyword,getUrl} from './utils'
const __dirname = path.dirname(import.meta.url)
// import cp from 'child_process';
const cleanProcessName = 'electron\\main\\test.js';
// const runtimeFolder = path.resolve() + path.sep;
// console.log(runtimeFolder,cleanProcessName,'00000');

// let cleanProcess = cp.fork(runtimeFolder+cleanProcessName);

const ProcessPool = new ChildProcessPool({
    path: path.join(app.getAppPath(), cleanProcessName), max: 6
});

// const staticThreadPool = new StaticThreadPool({})

class IpcMainEvent {
    on(eventName, callback) {
        ipcMain.on(eventName, callback)
    }

}
const taskList = []

let urls = new Map()
let getUrls = async (startIndex, keyword, url?) => {
    let res = await ProcessPool.send('task1', url, keyword)
    let htmlContent = res.result
    let $ = Cheerio.load(htmlContent, { baseURI: "https://cn.bing.com" });
    $('li.b_pag').find('a.b_widePag').not('a.sb_pagN').each((index, el) => {
        let url = el.attribs['href']
        if (index >= startIndex && !urls.has(url)) {
            urls.set(url, {
                url,
                isRunning: false,
                done: false,
                result: null
            })
            createTask(startIndex + 1, 'https://cn.bing.com' + url, keyword)
        }
    })
    return res
}


async function taskFn(index = 0, url, keyword) {
    return await getUrls(index, keyword, url)
}
function createTask(index = 0, url, keyword) {
    taskList.push(function () {
        return new Promise(async (resolve, reject) => {
            let res = await taskFn(index, url, keyword)
            resolve(res)
        })
    })
}

function runTask(index, event) {
    if (index < taskList.length) {
        return Promise.resolve()
    }
    return taskList[index]().then((res) => {
        event.reply('add-task', res.result)
        return runTask(index + 1, event)
    })
}
let u = function (n, t) {
    var r = new RegExp(
        "[?&]{1}" + t + "=([^&]+)([\\/\\\\][^?#]*)?([?#].*)?",
        "i"
    ),
        i = n.match(r);
    return i ? i[1] : null;
};
type Status = 'start' | 'running' | 'stop';
let TaskStatus: Status = 'start';
ipcMain.on('stop-task', async (event) => {
    TaskStatus = 'stop'
});

const piscina = new Piscina({
    filename: path.join(app.getAppPath(), 'electron\\main\\worker.js'),
});

piscina.on('message',()=>{
    console.log('eeeeee');
    
})


function isUrl(url) {
    try {
        return new URL(url)
    } catch (error) {
        return false
    }

}

class Queue {
    queue = []
    constructor() {
      this.queue = [];
    }
   
    enqueue(element) {
      this.queue.push(element);
    }

    enqueueMore(element=[]){
        this.queue.push(...element);
    }
   
    dequeue() {
      return this.queue.shift();
    }
   
    peek() {
      return this.queue[0];
    }

    includes(item){
        return this.queue.includes(item)
    }
   
    isEmpty() {
      return this.queue.length === 0;
    }
   
    size() {
      return this.queue.length;
    }
   
    clear() {
      this.queue = [];
    }
  }
   
  // 使用示例
  const q = new Queue();
  q.enqueue('John');
  q.enqueue('Sarah');
  q.enqueue('Jane');
   
  console.log(q.size()); // 输出: 3
  console.log(q.peek()); // 输出: John
   
  q.dequeue();
  console.log(q.peek()); // 输出: Sarah

ipcMain.on('add-task', async (event, keyword) => {
    TaskStatus = 'running'
    let urls = new Map()
    let getUrls = async (url = null, keyword, urls) => {
        if (TaskStatus !== 'stop') {
            // console.log(urls,'1111111111111111111111');

            const U = new Queue();
            const UTemp = new Array()
            // let getURL = async (url=null) => {
                console.log(url,444444444);
                
                let urls = U.queue
                let res = await ProcessPool.send('task1', { url, keyword })
                let htmlContent = res.result.data
                let $ = Cheerio.load(htmlContent, { baseURI: "https://cn.bing.com" });
                let lisDom = $('li.b_pag nav').find('a.b_widePag').not('a.sb_pagN')
                for (let index = 0; index < lisDom.length; index++) {
                    const el = lisDom[index];
                    let url = el.attribs['href']

                    if (url) {
                        let FPIG = u(url, 'FPIG')
                        url = url.replace('FPIG=' + FPIG, '')
                        // console.log(url,'ffffffffffffff');
                    console.log(urls,'00000000000000000');

                        if (!UTemp.includes(url)) {
                            console.log(UTemp.includes(url),url,'11111111111111111111111');
                            UTemp.push(url)
                            U.enqueue(url)
                            // const urlt = U.dequeue();


                            // const url = U.dequeue();
                    // // console.log(url,'fffffffs');
                    
                            let res = await getUrls('https://cn.bing.com' + url,keyword,urls)
                            res = res.map((item)=> !UTemp.includes(item)?item:false).filter(Boolean)
                            console.log(res,'fffffffs');

                            U.enqueueMore(res)
                    // console.log(url,'fffffffs');
                    
                            // let res = await getURL('https://cn.bing.com' + url)
                            // res = res.map((item)=> !UTemp.includes(item)?item:false).filter(Boolean)
                            // console.log(res,'fffffffs');

                            // U.enqueueMore(res)
                            // console.log(url,'dddddddddd');
                            // let res = await getURL('https://cn.bing.com' + url)
                            // res = res.map((item)=> !urls.includes(item)?item:false).filter(Boolean)
                            // urls.push(...res)
                        }else{
                            // continue
                        }
                    }
                }

                
                // for (let index = 0; index < U.size(); index++) {
                //     const url = U.dequeue();
                //     // // console.log(url,'fffffffs');
                    
                //     let res = await getUrls('https://cn.bing.com' + url,keyword,urls)
                //     res = res.map((item)=> !UTemp.includes(item)?item:false).filter(Boolean)
                //     console.log(res,'fffffffs');

                //     U.enqueueMore(res)
                // }

                // return urls
            // }

            // let res = await getURL()
            console.log(res,'333333333333333333333');
            
            const arr = [];

            urls.forEach(
                (value, key) => arr.push(value));
            // console.log(url,'ffffffffffffff');

            event.reply('urls', JSON.stringify(arr) || [])

            if ($('li.b_algo a.tilk').length) {
                let result = []

                let lisDom = $('li.b_algo')
                for (let index = 0; index < lisDom.length; index++) {
                    const el = $(lisDom[index]).find('h2 a')[0];
                    const desc = $(lisDom[index]).find('.b_caption')[0];
                    let url = el.attribs['href']
                    // console.log('dddddddddd');
                    if (url) {
                        let objItem = { url, title: $(el).text(), description: $(desc).text() } as any
                        let res = await piscina.run(url)
                        // let res = await ProcessPool.send('task1',{url})
                        let htmlContent = res?.data
                        if (htmlContent) {
                            let uri = new URL(url);
                            let $1 = Cheerio.load(htmlContent, { baseURI: uri.origin });

                            // console.log($1('a').attr('href'), url, 'sssssssss');
                            let a_tag = $1('a')
                            let a_href = []
                            for (let index = 0; index < a_tag.length; index++) {
                                const el = a_tag[index];
                                let url = el.attribs['href']
                                url = !isUrl(url) ? uri.origin + url : url
                                if (url && a_href.indexOf(url) >= 0) continue;
                                if (url && (url.includes('about') || url.includes('contact'))) {
                                    // let res = await piscina.run(url)
                                    a_href.push(url)
                                }
                            }

                            objItem.resource = a_href
                            result.push(objItem)
                            event.reply('add-task', JSON.stringify(result))

                            // console.log(a_href, 'qqqqqqqqqq');
                        }

                    }
                }
            }
            return res
        }

    }

    getUrls(null, keyword, urls)







    // return 


    //     try {

    //     /**
    //      * {
    //             url:'',
    //             isRunning:false,
    //             done:false,
    //             result: null
    //         }
    //         */
    //         let urls = new Map()
    //         let result = new Map()
    //         let urlTemp = {}
    //         let getUrls = async (startIndex,keyword,url?) => {
    //             let res = await ProcessPool.send('task1',url,keyword)
    //             let htmlContent = res.result
    //             let $ = Cheerio.load(htmlContent,{baseURI:"https://cn.bing.com"});
    //             let lisDom = $('li.b_pag').find('a.b_widePag').not('a.sb_pagN')
    //             for (let index = 0; index < lisDom.length; index++) {
    //                 const el = lisDom[index];

    //                 let url = el.attribs['href']
    //                 if (!urls.has(url)) {
    //                     if(index>=startIndex){
    //                         urls.set(url,{
    //                             url,
    //                             isRunning:false,
    //                             done:false,
    //                             result: null
    //                         })
    //                         // createTask(startIndex+1,'https://cn.bing.com'+url,keyword)
    //                     }
    //                     let item = urls.get(url)
    //                     if (!urlTemp[url]) {
    //                         urlTemp[url] = true
    //                         console.log(url,'99999999999999s',keyword)
    //                         let startIndext = startIndex+1
    //                         getUrls(startIndext,keyword,'https://cn.bing.com'+url).then((res)=>{
    //                             // if(!result.has(startIndex)){
    //                             //     result.set(startIndex,$('li.b_algo a').text())
    //                             //     if ($('li.b_algo a').text()) {
    //                             //         // console.log($('li.b_algo a'));

    //                             //         event.reply('add-task',$('li.b_algo a').text()||'sdf'+startIndex)
    //                             //     }
    //                             // }
    //                         })
    //                     }
    //                     if (item) {

    //                         // for (let item of urls.values() as any) {
    //                             // startIndex = startIndex+1
    //                             // getUrls(startIndex,keyword,'https://cn.bing.com'+item.url).then((res)=>{
    //                             //     // event.reply('add-task',startIndex)
    //                             // })
    //                         }
    //                     // }
    //                 }
    //             }

    //             if(!result.has(startIndex)){
    //                 result.set(startIndex,$('li.b_algo a').text())
    //                 if ($('li.b_algo a').text()) {
    //                     // console.log($('li.b_algo a'));

    //                     event.reply('add-task',$('li.b_algo a').text()||'sdf'+startIndex)
    //                 }
    //             }
    //             return res
    //         }

    //     let res = await getUrls(0,keyword)

    //     // createTask(0,`https://cn.bing.com/search?q=${keyword}&qs=n&FORM=BESBTB&sp=-1&lq=0&pq=oled&sc=13-4&cvid=9B7A3013D489406499B925984CC236EF&ghsh=0&ghacc=0&setlang=en&ensearch=1&cc=us`,keyword)

    //     // runTask(0,event)
    //     // console.log(taskList[0]);

    //     // console.log(urls.values(),'77778888888');
    //     // (async (item,el) => {
    //     //     console.log(el.attribs['href'],'fffffff');
    //     //     let res = await ProcessPool.send('task1',keyword)
    //     // })
    //     // console.log('sdfsfsdf',keyword);
    //     // cleanProcess.send({sdfsdf:'sfsdfsdfsdf'},(event)=>{
    //     //     console.log('oooooooooooooo',event);

    //     // })
    // } catch (error) {
    //     console.log('99999999999',error);

    // }
})
